<?php

namespace App\Http\Controllers\Api;

use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\Oauth;
use App\Models\Order;
use App\Models\Station;
use App\Models\PaymentInfo;
use Illuminate\Http\Request;
use App\Http\Requests\OrderRequest;
use App\Jobs\CloseOrder;
use Illuminate\Support\Facades\Redis;
use GuzzleHttp\Client;
use App\Models\Webinfo;
use App\Models\RechargeCardList;

class OrderController extends Controller
{
    /**
     * 生成订单号
     *  -当天从1开始自增
     *  -订单号模样：20190604000001
     * @param Client $redis
     * @param $key
     * @param $back：序号回退，如果订单创建失败，事务回滚可用
     * @return string
     */
    public static function createOrderNo($key, $userId)
    {
        $sn = Redis::get($key);
        $snDate = substr($sn,0,8);
        $snNo = intval(substr($sn, 14));
        $curDate = date('Ymd');
        $userId = sprintf("%06d",$userId);

        if(empty($sn)){
            $sn = $curDate.$userId.'000001';
        }else{
            $snNo = ($curDate==$snDate) ? ($snNo+1) : 1;
            $sn = $curDate.$userId.sprintf("%06d",$snNo);
        }

        // if($back==1){//序号回退
        //     if($curDate==$snDate){
        //         $snNo = ($snNo>1) ? ($snNo-1) : 1;
        //         $sn = $curDate.sprintf("%06d",$snNo);
        //     }
        // }else{//序号增加
        //     if(empty($sn)){
        //         $sn = $curDate.$userId.'000001';
        //     }else{
        //         $snNo = ($curDate==$snDate) ? ($snNo+1) : 1;
        //         $sn = $curDate.sprintf("%06d",$snNo);
        //     }
        // }
        Redis::set($key, $sn);
        return $sn;
    }

    // 生成订单
    /**
     * order_status: 
     * 1 待付款，
     * 2 已支付、未使用，
     * 3 已使用，
     * 7 已作废，
     * 8 已过期，
     * 9 已取消
    */
    // 一键充值订单
    public function createOrder(OrderRequest $request) {
        $userAuth = Auth::guard('api')->user();
        $user = User::find($userAuth->user_id);

        $orderId = $this->createOrderNo('order_id', $userAuth->user_id);

        $phone =  $request->phone ?? $user->phone;
        $stationId = $request->station_id;
        // 优惠后的价格
        $station = $this->getDiscount($stationId);
        $amount = round($request->order_amount * $station->discount);

        $data = $request->all();
        
        $data['order_type'] = '1';
        $data['order_id'] = $orderId;
        $data['user_id'] = $userAuth->user_id;
        $data['amount'] = $amount;
        $data['station_id'] = $stationId;
        $data['gas_original_price'] = $station->nation_price;
        $data['gas_now_price'] = $station->now_price;
        $data['phone'] = $phone;
        $data['order_status'] = 1;

        $order = Order::create($data);

        // 开启队列，半小时未付款取消订单
        CloseOrder::dispatch($order, config('app.order_close'));
        // $this->dispatch(new CloseOrder($order, config('app.order_close')));

        // 获取微信支付
        return $this->wechatPayment($order);
    }

    // 获取加油站优惠折扣
    public static function getDiscount($stationId) {
        $station = Station::where('code_id', $stationId)->first();
        $Webinfo = Webinfo::first();

        if (!$station) return $this->failed('加油站不存在!', 200);

        if (!$station->now_price) {
            $station->now_price = $Webinfo->price_0_now;
        }
        if (!$station->nation_price) {
            $station->nation_price = $Webinfo->price_0_nation;
        }
        $station->discount = $station->now_price / $station->nation_price;
        if ($station->discount > 1) {
            $station->discount = 1;
        }

        return $station;
    }

    // 油卡充值订单
    /**
     * order_status: 
     * 1 待付款，
     * 2 已支付、待审核，
     * 5 审核通过，
     * 6 审核拒绝，
     * 9 已取消
    */
    public function createRechargeOrder(Request $request) {
        $userAuth = Auth::guard('api')->user();
        $user = User::find($userAuth->user_id);
        $orderId = $this->createOrderNo('order_id', $userAuth->user_id);
        $phone =  $request->phone ?? $user->phone;

        $card_type = $request->card_type;   // 实体卡 虚拟卡 
        $card_num = $request->common_number . $request->last_number;
        $order_amount = $request->order_amount;

        $data = $request->all();
        $data['order_type'] = '2';
        $data['order_id'] = $orderId;
        $data['amount'] = $order_amount;
        $data['user_id'] = $userAuth->user_id;
        $data['phone'] = $phone;
        $data['order_status'] = 1;
        $data['card_num'] = $card_num;

        $order = Order::create($data);

        $cardInfo = [
            'user_id' => $userAuth->user_id,
            'common_number' => $request->common_number,
            'last_number' => $request->last_number,
            'card_type' => $request->card_type
        ];
        RechargeCardList::updateOrCreate($cardInfo, $cardInfo);
        // 开启队列，半小时未付款取消订单
        CloseOrder::dispatch($order, config('app.order_close'));
        // 获取微信支付
        return $this->wechatPayment($order, 'gas-recharge');
    }

    // 审核通过油卡充值订单 5通过 6拒绝
    public function audit(OrderRequest $request) {
        $order = Order::where(['order_id' => $request->order_id, 'order_type' => '油卡充值'])->first();
        if ($order->order_status == 2) {
            $order->update([
                'order_status' => $request->status,
                'reason' => $request->reason
            ]);
            return $this->message($request->status == 5 ? '订单审核通过!' : '订单已拒绝！');
        }
        return $this->failed('订单状态异常，无法审核！', 200);
    }

    // 取消订单
    public function cancelOrder(OrderRequest $request) {
        $order = Order::where('order_id', $request->order_id)->first();

        if ($order->order_status == 1) {
            $order->update(['order_status' => 9]);
            return $this->message('订单已取消!');
        }
        return $this->failed('当前无法取消订单!', 200);
    }

    // 个人订单列表
    public function orderList(Request $request) {
        $order_status = $request->order_status;
        $order_type = $request->order_type;
        $userAuth = Auth::guard('api')->user();

        $params = ['user_id' => $userAuth->user_id];

        // 不传参数默认查询所有
        if ($order_status) {
            $params['order_status'] = $order_status;
        }
        if ($order_type) {
            $params['order_type'] = $order_type;
        }
        $orders = Order::where($params)->orderBy('created_at', 'desc')->paginate(10);

        foreach($orders as $item){
            if ($item->order_status == 1) {
                $item->nowTime = time();
                $item->created_at_count = strtotime($item->created_at);
                // 订单取消倒计时
                $item->count = strtotime($item->created_at) + 1800 - time();
            }
        }

        return $this->success($orders);
    }

    // 订单详情
    public function detail(Request $request) {
        $order = Order::where('order_id', $request->order_id)->orderBy('created_at', 'desc')->first();

        if ($order->order_status == 1) {
            $order->nowTime = time();
            $order->created_at_count = strtotime($order->created_at);
            $order->count = strtotime($order->created_at) + 1800 - time();
        }
        $order->stationInfo = Station::where('code_id', $order->station_id)->first();

        return $this->success($order);
    }

    // 所有人订单
    public function allOrderList(Request $request) {
        $data = [];
        if ($request->order_type) {
            $data['order_type'] = $request->order_type;
        }
        $orders = Order::where($data)->orderBy('created_at', 'desc')->paginate(10);
        return $this->success($orders);
    }

    // 汇卡支付
    public function wechatPayment($order, $type = 'gas-qrCode') {
        $client = new Client();

        $openId = '';
        $userAuth = Auth::guard('api')->user();
        $oauth = Oauth::where('user_id', $userAuth->user_id)->first();
        if (!$oauth) {
            return $this->failed('请先微信授权！', 200);
        } else {
            $openId = $oauth->oauth_id;
        }

        $url = env('WECHAT_PAYMENT_URL').'hicardpay/order/create';
        $json = [
            "amount" => sprintf("%d", $order->amount),
            // "amount" => strval(random_int(1, 10)),
            "backEndUrl" => config('app.url')."/payment/callback",
            "bizType" => "814",
            "frontEndUrl" => config('app.frontEndUrl'),
            "goodsName" => $type,
            "hicardMerchNo" => env('WECHAT_PAYMENT_MERCHANT_ID'),
            "isT0" => "1",
            "merchOrderNo" => $order->order_id,
            "openId" => $openId,
            "organNo" => env('WECHAT_PAYMENT_ORGANNO'),
            "payType" => "014",
            "subAppId" => env('WECHAT_APPID'),
            "version" => "V003"
        ];

        $json = $this->sign($json);

        $response = $client->request('POST', $url, [
            'headers' => [
                'Content-Type'=>'application/json;charset=UTF-8'
            ],
            'json' => $json
        ]);
        $data = json_decode($response->getBody()->getContents());
        $PaymentInfoController = new PaymentInfoController();
        $PaymentInfoController->create($userAuth->user_id, $oauth->oauth_id, $data);
        return $this->success($data);
    }

    // 订单支付状态查询
    public function paymentStatus(Request $request) {
        $client = new Client();
        $order_id = $request->order_id;
        $time = $request->create_time;
        $hicardOrderNo = $request->hicardOrderNo;
        $url = env('WECHAT_PAYMENT_URL').'hicardpay/order/query';
        $json = [
            "createTime" => $time,
            "hicardMerchNo" => env('WECHAT_PAYMENT_MERCHANT_ID'),
            "hicardOrderNo" => $hicardOrderNo,
            "merchOrderNo" => $order_id,
            "organNo" => env('WECHAT_PAYMENT_ORGANNO'),
            "version" => "V003"
        ];

        $json = $this->sign($json);

        $response = $client->request('POST', $url, [
            'headers' => [
                'Content-Type'=>'application/json;charset=UTF-8'
            ],
            'json' => $json
        ]);
        return $this->success(json_decode($response->getBody()->getContents()));
    }

    public static function sign($json) {
        $string = '';
        foreach($json as $key => $value) {
            $string .=  $key.'='.$value.'&';
        }
        $sign = $string . env('WECHAT_PAYMENT_SIGN');
        $json['sign'] = md5($sign);
        return $json;
    }
    // 订单搜索
    public function search(Request $request) {
        $order_id = $request->order_id;
        $phone = $request->phone;
        $date = $request->date;
        $status = $request->status;
        $amount = $request->amount;
        $order_type = $request->order_type ?? '一键加油';
        $orders = [];

        if ($order_id) {
            $orders = Order::where('order_id', $order_id)->paginate(10);
        } else if ($phone) {
            $orders = Order::where([
                'phone'=> $phone,
                'order_type' => $order_type
            ])->orderBy('created_at', 'desc')->paginate(10);
        } else if ($date) {
            $orders = Order::whereDate('created_at', $date)
                ->where(['order_type' => $order_type])
                ->orderBy('created_at', 'desc')->paginate(10);
        } else if ($status) {
            $orders = Order::where([
                'order_status' => $status,
                'order_type' => $order_type
            ])->orderBy('created_at', 'desc')->paginate(10);
        } else if ($amount) {
            $orders = Order::where([
                'order_amount' => $amount,
                'order_type' => $order_type
            ])->orderBy('created_at', 'desc')->paginate(10);
        }
        
        return $this->success($orders);  
    }

    // 作废订单
    public function failureOrder(Request $request) {
        $order = Order::where([
            'order_id' => $request->order_id, 
            'order_status' => 2
        ])->first();
        if (!$order) return $this->failed('不能作废该订单!', 200);
        $order->order_status = 7;
        $order->save();
        return $this->message('订单已失效！');
    }
}
